<template>
  <div>
    <el-form :model="formConfig" size="small" label-position="left" label-width="120px"
             class="setting-form" @submit.prevent>
      <el-collapse v-model="formActiveCollapseNames" class="setting-collapse">
        <el-collapse-item name="1" :title="i18nt('designer.setting.basicSetting')">
          <el-form-item label="护理单编号">
            <el-input v-model="formConfig.funcNo" disabled></el-input>
          </el-form-item>
          <el-form-item label="护理单名称">
            <el-input v-model="formConfig.frame.title" disabled></el-input>
          </el-form-item>
          <el-form-item label="保存主表">
            <el-select v-model="formConfig.masterRecordTableName" @change="changeMasterTable" filterable>
              <el-option :value="item.MAINTABLE" v-for="(item,index) in reportList" :label="item.REMARK"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="保存子表">
            <el-input v-model="formConfig.childRecordTableName" disabled></el-input>
          </el-form-item>
          <el-form-item label="工具栏">
            <el-button type="primary"  @click="editToolBar()">编辑工具栏</el-button>
          </el-form-item>
<!--          <el-form-item label="加载顺序">
            <el-input-number v-model="formConfig.showIndex"></el-input-number>
          </el-form-item>-->
          <el-form-item label="窗口布局" prop="funcLayout">
            <el-select v-model="formConfig.funcLayout" placeholder="请选择窗口布局">
              <el-option v-for="item in funcLayoutList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="展示标题">
            <el-switch v-model="formConfig.frame.showTitle"></el-switch>
          </el-form-item>
          <el-form-item label="标题对齐">
            <el-radio-group v-model="formConfig.frame.titleAlign">
              <el-radio-button label="居左" value="left" />
              <el-radio-button label="居中" value="center" />
              <el-radio-button label="居右" value="right" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="二级标题">
            <el-input v-model="formConfig.frame.subTitle"></el-input>
          </el-form-item>
          <el-form-item label="是否分页">
            <el-switch v-model="formConfig.pagination"></el-switch>
          </el-form-item>
<!--          <el-form-item label="是否缩放">
            <el-switch v-model="formConfig.frame.resizeAble"></el-switch>
          </el-form-item>
          <el-form-item label="可否拖动">
            <el-switch v-model="formConfig.frame.dragAble"></el-switch>
          </el-form-item>
          <el-form-item label="最大最小">
            <el-switch v-model="formConfig.frame.maxMinAble"></el-switch>
          </el-form-item>-->
          <el-form-item label="可否打印">
            <el-switch v-model="formConfig.frame.printAble"></el-switch>
          </el-form-item>
<!--          <el-form-item label="是否全屏">
            <el-switch v-model="formConfig.frame.fullScreen"></el-switch>
          </el-form-item>-->
<!--          <el-form-item label="填写说明">
            <el-button type="primary"  @click="editFillText()">编辑描述</el-button>
          </el-form-item>-->
<!--          <el-divider class="custom-divider-margin-top">打印设置</el-divider>
          <el-form-item label="纸张类型">
            <el-select v-model="formConfig.frame.printSetting.pageSize" @change="changePageSize">
              <el-option value="A4">A4</el-option>
              <el-option value="B5">B5</el-option>
              <el-option value="自定义">自定义</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="页面宽度">
            <el-input-number v-model="formConfig.frame.printSetting.pageWidth"
                             :precision="2" :disabled="formConfig.frame.printSetting.pageSize != '自定义'"></el-input-number>
          </el-form-item>
          <el-form-item label="页面高度">
            <el-input-number v-model="formConfig.frame.printSetting.pageHeight"
                             :precision="2" :disabled="formConfig.frame.printSetting.pageSize != '自定义'"></el-input-number>
          </el-form-item>
          <el-form-item label="页面方向">
            <el-radio-group v-model="formConfig.frame.printSetting.pageDirection">
              <el-radio value="H">纵向</el-radio>
              <el-radio value="V">横向</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="医院编码">
            <el-input v-model="formConfig.frame.printSetting.companyCode" disabled></el-input>
          </el-form-item>
          <el-form-item label="医院名称">
            <el-input v-model="formConfig.frame.printSetting.companyName" disabled></el-input>
          </el-form-item>
          <el-form-item label="表单ISO编码">
            <el-input v-model="formConfig.frame.printSetting.reportISO" disabled></el-input>
          </el-form-item>-->
          <el-divider class="custom-divider-margin-top">自定义sql</el-divider>
          <el-row
                  :key="index" style="width: 100%;margin-bottom: 5px;display: flex;">
            <el-form-item label-width="0">
              <div v-for="(item,index) in formConfig.customDBStatement" :key="index" style="width: 100%;margin-bottom: 5px">
                <el-button type="primary" style="min-width: 150px" @click="editSql(item,index)">{{ item.statementName }}</el-button>
                <el-button circle plain size="small" type="danger"
                           icon="el-icon-minus" class="col-delete-button" @click="deleteSql(index)"></el-button>
              </div>
              <el-button link type="primary" @click="addSql()" style="margin-left: 10px;">新增</el-button>
            </el-form-item>
          </el-row>
          <el-divider class="custom-divider-margin-top">返回数据</el-divider>
<!--          <el-form-item label="参数拼接">
            <el-switch v-model="formConfig.returnParams.split"></el-switch>
          </el-form-item>
          <el-form-item label-width="0">
            <div v-for="(item,index) in formConfig.returnParams.args" :key="index" style="width: 100%">
              <el-input v-model="formConfig.returnParams.args[index]" size="small"
                        style="width: 200px;margin: 10px;margin-top: 0px"></el-input>
              <el-button circle plain size="small" type="danger"
                         icon="el-icon-minus" class="col-delete-button" @click="deleteReturnParams(index)"></el-button>
            </div>
            <el-button link type="primary" @click="addReturnParams" style="margin-left: 10px;">增加参数</el-button>
          </el-form-item>-->
          <el-row v-for="(item,index) in formConfig.returnParams"
                  :key="index" style="width: 100%;margin-bottom: 5px;display: flex;">
            <el-col :span="12">
              <el-form-item label="表达式" label-width="40" >
                <el-input v-model="item.expression">
                  <template #append>
                    <el-button @click="goEditReturnParam(item)" size="small">...</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="Key" label-width="25" >
                <el-input v-model="item.field">
                  <template #append>
                    <el-button @click="goEditFuncKey(item)" size="small">...</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button circle plain size="small" type="danger"
                         icon="el-icon-minus" class="col-delete-button" @click="deleteReturnParams(index)"></el-button>
            </el-col>
          </el-row>
          <el-button link type="primary" @click="addReturnParams" style="margin-left: 10px;">增加参数</el-button>
          <el-divider class="custom-divider-margin-top">顶部按钮</el-divider>
          <el-form-item label-width="0">
            <div v-for="(item,index) in formConfig.btnBar.topBtns" :key="index" style="width: 100%;margin-bottom: 5px">
              <el-button type="primary" style="min-width: 150px" @click="editBtn('top',item,index)">{{ item.showName }}</el-button>
              <el-button circle plain size="small" type="primary" :disabled="index == 0"
                         icon="el-icon-top" class="col-delete-button" @click="moveUp('top',index)"></el-button>
              <el-button circle plain size="small" type="primary" :disabled="formConfig.btnBar.topBtns.length == index+1"
                         icon="el-icon-bottom" class="col-delete-button" @click="moveDown('top',index)"></el-button>
              <el-button circle plain size="small" type="danger"
                         icon="el-icon-minus" class="col-delete-button" @click="deleteBtns('top',index)"></el-button>
            </div>
            <el-button link type="primary" @click="addBtn('top')" style="margin-left: 10px;">增加按钮</el-button>
          </el-form-item>
          <el-divider class="custom-divider-margin-top">内部按钮</el-divider>
          <el-form-item label-width="0">
            <div v-for="(item,index) in formConfig.btnBar.inBtns" :key="index" style="width: 100%;margin-bottom: 5px">
              <el-button type="primary" style="min-width: 150px" @click="editBtn('in',item,index)">{{ item.showName }}</el-button>
              <el-button circle plain size="small" type="primary" :disabled="index == 0"
                         icon="el-icon-top" class="col-delete-button" @click="moveUp('in',index)"></el-button>
              <el-button circle plain size="small" type="primary" :disabled="formConfig.btnBar.inBtns.length == index+1"
                         icon="el-icon-bottom" class="col-delete-button" @click="moveDown('in',index)"></el-button>
              <el-button circle plain size="small" type="danger"
                         icon="el-icon-minus" class="col-delete-button" @click="deleteBtns('in',index)"></el-button>
            </div>
            <el-button link type="primary" @click="addBtn('in')" style="margin-left: 10px;">增加按钮</el-button>
          </el-form-item>
          <el-divider class="custom-divider-margin-top">底部按钮</el-divider>
          <el-form-item label-width="0">
            <div v-for="(item,index) in formConfig.btnBar.bottomBtns" :key="index" style="width: 100%;margin-bottom: 5px">
              <el-button type="primary" style="min-width: 150px" @click="editBtn('bottom',item,index)">{{ item.showName }}</el-button>
              <el-button circle plain size="small" type="primary" :disabled="index == 0"
                         icon="el-icon-top" class="col-delete-button" @click="moveUp('bottom',index)"></el-button>
              <el-button circle plain size="small" type="primary" :disabled="formConfig.btnBar.bottomBtns.length == index+1"
                         icon="el-icon-bottom" class="col-delete-button" @click="moveDown('bottom',index)"></el-button>
              <el-button circle plain size="small" type="danger"
                         icon="el-icon-minus" class="col-delete-button" @click="deleteBtns('bottom',index)"></el-button>
            </div>
            <el-button link type="primary" @click="addBtn('bottom')" style="margin-left: 10px;">增加按钮</el-button>
          </el-form-item>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <el-dialog title="编辑按钮" v-model="openBtn" width="1200" append-to-body>
      <el-form ref="btnForm" :model="btnForm" :rules="btnRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="按钮ID" prop="btnId">
              <el-input v-model="btnForm.btnId" placeholder="请输入按钮ID"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="按钮类型" prop="btnType">
              <el-select v-model="btnForm.btnType" placeholder="请输入按钮类型" clearable filterable @change="changeBtnType">
                <el-option
                    v-for="item in btnTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="按钮名称" prop="showName">
              <el-input v-model="btnForm.showName" placeholder="请输入按钮名称" :disabled="btnForm.btnType != 'custom'"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宽度" prop="width">
              <el-input v-model="btnForm.width" placeholder="请输入宽度"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="高度" prop="height">
              <el-input v-model="btnForm.height" placeholder="请输入高度"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标" prop="icon">
              <el-input v-model="btnForm.icon" placeholder="请输入图标"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="展示顺序" prop="ord">
              <el-input-number v-model="btnForm.ord" placeholder="请输入展示顺序" style="width: 200px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="窗口号" prop="winNo">
              <el-input v-model="btnForm.winNo" placeholder="请输入窗口号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表单号" prop="funcNo">
              <el-input v-model="btnForm.funcNo" placeholder="请输入窗口号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色代码" prop="btnRoles">
              <el-input v-model="btnForm.btnRoles" placeholder="请输入角色代码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行存储过程" prop="callProc">
              <el-switch v-model="btnForm.callProc"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跳转组件" prop="component">
              <el-input v-model="btnForm.component" placeholder="请输入跳转组件"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="自定义参数" prop="customData" v-if="btnForm.btnType == 'custom'">
              <el-input v-model="btnForm.customData" placeholder="请输入自定义参数"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="btnForm.callProc">
            <el-form-item label="存储过程" prop="proc">
              <el-input type="textarea" v-model="btnForm.proc"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="submitBtnForm">确 定</el-button>
        <el-button @click="openBtn = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑工具栏" v-model="openToolBar" width="1200" append-to-body>
      <el-form ref="toolBarForm"  label-width="80px">
        <el-row v-for="(item,index) in formConfig.toolBar" :key="index">
          <el-col :span="7">
            <el-form-item label="位置" prop="position">
              <el-radio-group v-model="item.position">
                <el-radio-button label="左" value="left" />
                <el-radio-button label="右" value="right" />
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="控件名称" prop="controlName">
              <el-radio-group v-model="item.controlName">
                <el-radio-button label="时间选择框" value="datePickers" />
                <el-radio-button label="搜索框" value="searchBox" />
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="默认值" prop="defaultValue">
              <el-select v-model="item.defaultValue">
                <el-option label="从住院时起" value="-1" />
                <el-option label="从昨天起" value="1" />
                <el-option label="从三天前起" value="3" />
                <el-option label="从七天前起" value="7" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button circle plain size="small" type="danger"
                       icon="el-icon-minus" class="col-delete-button" @click="deleteToolBar(index)"></el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="1">
            <el-button link type="primary" @click="addToolBar()" style="margin-left: 10px;">增加组件</el-button>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="openToolBar = false">完 成</el-button>
      </div>
    </el-dialog>

    <el-dialog title="填写说明" v-model="openText" width="1200" append-to-body>
<!--      <quill-editor
          ref="fieldEditor"
          :options="editorOptions"
          style="height: 500px;margin-bottom: 30px"
          v-model:value="helpDocument"></quill-editor>-->
      <wang-editor
          style="border: 1px solid gainsboro"
          v-model="helpDocument"
      />
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="submitTextForm">确 定</el-button>
        <el-button @click="openText = false">取 消</el-button>
      </div>
    </el-dialog>

    <div v-if="showFormEventDialogFlag" class="" v-drag="['.drag-dialog.el-dialog', '.drag-dialog .el-dialog__header']">
      <el-dialog :title="i18nt('designer.setting.editFormEventHandler')" v-model="showFormEventDialogFlag"
                 :show-close="true" class="drag-dialog small-padding-dialog" append-to-body
                 :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true">
        <el-alert type="info" :closable="false" :title="'form.' + eventParamsMap[curEventName]"></el-alert>
        <code-editor :mode="'javascript'" :readonly="false" v-model="formEventHandlerCode" ref="ecEditor"></code-editor>
        <el-alert type="info" :closable="false" title="}"></el-alert>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showFormEventDialogFlag = false">
              {{i18nt('designer.hint.cancel')}}</el-button>
            <el-button type="primary" @click="saveFormEventHandler">
              {{i18nt('designer.hint.confirm')}}</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <div v-if="showEditFormCssDialogFlag" class="" v-drag="['.drag-dialog.el-dialog', '.drag-dialog .el-dialog__header']">
      <el-dialog :title="i18nt('designer.setting.formCss')" v-model="showEditFormCssDialogFlag"
                 :show-close="true" class="drag-dialog small-padding-dialog" append-to-body
                 :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true">
        <code-editor :mode="'css'" :readonly="false" v-model="formCssCode"></code-editor>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showEditFormCssDialogFlag = false">
              {{i18nt('designer.hint.cancel')}}</el-button>
            <el-button type="primary" @click="saveFormCss">
              {{i18nt('designer.hint.confirm')}}</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <div v-if="showEditFunctionsDialogFlag" class="" v-drag="['.drag-dialog.el-dialog', '.drag-dialog .el-dialog__header']">
      <el-dialog :title="i18nt('designer.setting.globalFunctions')" v-model="showEditFunctionsDialogFlag"
                 :show-close="true" class="drag-dialog small-padding-dialog" append-to-body
                 :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true">
        <code-editor :mode="'javascript'" :readonly="false" v-model="functionsCode" ref="gfEditor"></code-editor>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showEditFunctionsDialogFlag = false">
              {{i18nt('designer.hint.cancel')}}</el-button>
            <el-button type="primary" @click="saveGlobalFunctions">
              {{i18nt('designer.hint.confirm')}}</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <el-dialog title="自定义sql" v-model="openSql" append-to-body width="1200">
      <el-form ref="form" :model="sqlForm">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="名称" prop="statementName">
              <el-input v-model="sqlForm.statementName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类型" prop="statementType">
              <el-select v-model="sqlForm.statementType" placeholder="请选择类型">
                <el-option label="sql表达式" value="sql" />
                <el-option label="函数" value="function" />
                <el-option label="存储过程" value="procedure" />
                <el-option label="后端接口" value="api" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数据源" prop="dataSourceKey">
              <el-select v-model="sqlForm.dataSourceKey" placeholder="请选择数据源">
                <el-option v-for="item in dataSourceList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider>输入参数</el-divider>
        <el-row v-for="(item,index) in sqlForm.inArgs" :key="index" :gutter="20">
          <el-col :span="10">
            <el-form-item label="输入参数名" prop="inArgsPre">
              <el-input v-model="item.argName" placeholder="请录入输入参数名">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="输入参数值" prop="inArgsPre">
              <el-input v-model="item.argValue" placeholder="请录入输入参数值">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" plain @click="addArgs(sqlForm.inArgs)"><el-icon><Plus/></el-icon></el-button>
            <el-button type="primary" plain @click="deleteArgs(sqlForm.inArgs,index)"><el-icon><Minus/></el-icon></el-button>
          </el-col>
        </el-row>
        <el-divider>输出参数</el-divider>
        <el-row v-for="(item,index) in sqlForm.outArgs" :key="index" :gutter="20">
          <el-col :span="10">
            <el-form-item label="输出参数名">
              <el-input v-model="item.argName" placeholder="请录入输出参数名">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="输出参数值">
              <el-input v-model="item.argValue" placeholder="请录入输出参数值">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" plain @click="addArgs(sqlForm.outArgs)"><el-icon><Plus/></el-icon></el-button>
            <el-button type="primary" plain @click="deleteArgs(sqlForm.outArgs,index)"><el-icon><Minus/></el-icon></el-button>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="16">
            <el-input v-model="sqlForm.statement"
                      :rows="20"
                      type="textarea"
                      ref="sqlInput"
                      placeholder="请输入自定义sql"></el-input>
          </el-col>
          <el-col :span="8" >
            <el-input v-model="calculationFilterString"
                      placeholder="搜索"></el-input>
            <div class="calculationFilter topCalculationFilter">
              <div v-for="item in calculationFieldList" :key="item" @click="selectSqlField(item)">{{item}}</div>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="submitSql">确 定</el-button>
        <el-button @click="openSql = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="计算表达式" v-model="openCalculation" append-to-body width="1200">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-input v-model="calculation"
                    :rows="20"
                    type="textarea"
                    ref="calculationInput"
                    placeholder="请输入表达式"></el-input>
        </el-col>
        <el-col :span="8" >
          <el-input v-model="calculationFilterString"
                    placeholder="搜索"></el-input>
          <div class="calculationFilter topCalculationFilter">
            <div v-for="item in calculationFieldList" :key="item" @click="selectCalculationField(item)">{{item}}</div>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="submitCalculation">确 定</el-button>
        <el-button @click="openCalculation = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择护理单KEY" v-model="openFuncKey" append-to-body width="500">
      <el-form-item label="护理单">
        <el-select v-model="functionNo" clearable placeholder="请选择护理单" @change="changeFunc" filterable>
          <el-option :label="item.frame.title" :value="item.funcNo" :key="item.funcNo" v-for="item in funcList"/>
        </el-select>
      </el-form-item>
      <el-form-item label="对应Key">
        <el-select v-model="functionField" clearable placeholder="请选择字段" filterable>
          <el-option :label="item.label+'/'+item.fieldName" :value="item.fieldName" :key="item.fieldName" v-for="item in funcFieldList"/>
        </el-select>
      </el-form-item>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="submitFuncKey">确 定</el-button>
        <el-button @click="openFuncKey = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import i18n from "@/utils/i18n"
  import CodeEditor from '@/components/code-editor/index'
  import {deepClone, generateId, generateUUID, insertCustomCssToHead, insertGlobalFunctionsToHtml} from "@/utils/util"
/*  import { Quill, quillEditor } from 'vue3-quill'*/
  import WangEditor from  "@/components/WangEditor/index.vue"
  export default {
    name: "form-setting",
    mixins: [i18n],
    components: {
      CodeEditor,
/*      quillEditor,*/
      WangEditor,
    },
    props: {
      designer: Object,
      formConfig: Object,
    },
    inject: ['getDesignerConfig','getFieldWidgets','getNursingSheetList','getReportTypeDict','getCommDictDetailList'],
    data() {
      return {
        dataSourceList:[],
        funcLayoutList:[],
        openText:false,
        helpDocument:"",
        openToolBar:false,

        openCalculation:false,
        calculationFilterString:"",
        calculation:"",
        selectReturnItem:{},

        openFuncKey:false,
        selectFuncKeyItem:{},
        funcList:[],
        funcFieldList:[],
        functionNo:null,
        functionField:null,
        reportList:[],

        openBtn: false,
        btnForm: {},
        btnTypeOptions:[
          {
            value: 'save',
            label: '保存',
          },
          {
            value: 'add',
            label: '新增',
          },
          {
            value: 'delete',
            label: '删除',
          },
          {
            value: 'update',
            label: '修改',
          },
          {
            value: 'cancel',
            label: '取消',
          },
          {
            value: 'print',
            label: '打印',
          },
          {
            value: 'printview',
            label: '打印预览',
          },
          {
            value: 'history',
            label: '查看历史',
          },
          {
            value: 'search',
            label: '查询',
          },
          {
            value: 'loadLastRec',
            label: '加载上一条记录',
          },
          {
            value: 'custom',
            label: '自定义',
          },
        ],
        buttonMode:null,
        buttonType:null,
        buttonIndex:0,
        btnRules: {
          btnId: [
            { required: true, message: '按钮ID必填', trigger: 'blur' }
          ],
          showName: [
            { required: true, message: '按钮名称必填', trigger: 'blur' }
          ],
        },
        sqlMode:null,
        sqlIndex:0,
        sqlForm:{},
        openSql:false,
        designerConfig: this.getDesignerConfig(),

        formActiveCollapseNames: ['1', '2'],

        formSizes: [
          {label: 'default', value: ''},
          {label: 'large', value: 'large'},
          //{label: 'medium', value: 'medium'},
          {label: 'small', value: 'small'},
          //{label: 'mini', value: 'mini'},
        ],
        pageOptions:["A4","B5","自定义"],

        showEditFormCssDialogFlag: false,
        formCssCode: '',
        cssClassList: [],

        showEditFunctionsDialogFlag: false,
        functionsCode: '',

        showFormEventDialogFlag: false,
        formEventHandlerCode: '',
        curEventName: '',

        eventParamsMap: {
          'onFormCreated':      'onFormCreated() {',
          'onFormMounted':      'onFormMounted() {',
          'onFormDataChange':   'onFormDataChange(fieldName, newValue, oldValue, formModel, subFormName, subFormRowIndex) {',
          'onFormValidate':     'onFormValidate(formModel) {',
        },
        /*editorOptions:{
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
              ['blockquote', 'code-block'],

              [{ 'header': 1 }, { 'header': 2 }],               // custom button values
              [{ 'list': 'ordered'}, { 'list': 'bullet' }],
              [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
              [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
              [{ 'direction': 'rtl' }],                         // text direction

              [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

              [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
              [{ 'font': [] }],
              [{ 'align': [] }],

              ['clean']                                         // remove formatting button
            ]
          },
          placeholder: 'Compose an epic...',
          theme: 'snow'
        }*/
      }
    },
    created() {
      //导入表单JSON后需要重新加载自定义CSS样式！！！
      this.designer.handleEvent('form-json-imported', () => {
        this.formCssCode = this.formConfig.cssCode
        insertCustomCssToHead(this.formCssCode)
        this.extractCssClass()
        this.designer.emitEvent('form-css-updated', deepClone(this.cssClassList))
      })
    },
    mounted() {
      /* SettingPanel和FormWidget为兄弟组件, 在FormWidget加载formConfig时，
         此处SettingPanel可能无法获取到formConfig.cssCode, 故加个延时函数！ */
      setTimeout(() => {
        this.formCssCode = this.formConfig.cssCode
        insertCustomCssToHead(this.formCssCode)
        this.extractCssClass()
        this.designer.emitEvent('form-css-updated', deepClone(this.cssClassList))
      }, 1200)
      let nursingSheetList = this.getNursingSheetList()
      let funcList = []
      nursingSheetList.forEach(function (val){
        if (val.CONFIG_JSON){
          try {
            funcList.push(JSON.parse(val.CONFIG_JSON))
          }catch (e) {
            console.log(val.CONFIG_JSON)
          }
        }
      })
      this.funcList = funcList;
      this.initReportList();
      this.initDataSourceList()
      this.initFuncLayoutList()
    },
    computed: {
      calculationFieldList(){
        let fields = [];
        this.getFieldWidgets().forEach(function (val){
          if (val.type != "static-text"){
            fields.push(val.field.options.fieldName+"/"+val.field.options.label)
          }
        })
        return fields.filter(item => item.includes(this.calculationFilterString))
      },
    },
    methods: {
      async initFuncLayoutList() {
        let dicDetailList = await this.getCommDictDetailList("funcLayoutDict");
        let option = []
        dicDetailList.forEach(function (val) {
          option.push({
            label: val.ITEM_NAME,
            value: val.ITEM_CODE,
          })
        })
        this.funcLayoutList = option;
      },
      async initDataSourceList() {
        let dicDetailList = await this.getCommDictDetailList("externalDbDict");
        let option = []
        dicDetailList.forEach(function (val) {
          option.push({
            label: val.ITEM_NAME,
            value: val.ITEM_CODE,
          })
        })
        this.dataSourceList = option;
      },
      async initReportList() {
        if (localStorage.getItem("accessToken")) {
          this.reportList = await this.getReportTypeDict();
        }
      },
      changeMasterTable(val){
        let report = null;
        this.reportList.forEach(function (item) {
          if (val == item.MAINTABLE){
            report = item
          }
        })
        if (report){
          this.formConfig.childRecordTableName = report.SUBTABLE;
        }
      },
      changeFunc(funcno){
        let func = null;
        this.funcList.forEach(function (value) {
          if (funcno == value.funcNo){
            func = value;
          }
        })
        let formFieldDefs = func.formDef.formFieldDefs;
        let funcFieldList = [];
        formFieldDefs.forEach(function (val){
          if (val.type != "static-text"){
            funcFieldList.push(val)
          }
        })
        this.funcFieldList = funcFieldList
      },
      editToolBar(){
        this.openToolBar = true;
      },
      addToolBar(){
        this.formConfig.toolBar.push({defaultValue:"-1"});
      },
      deleteToolBar(index){
        this.formConfig.toolBar.splice(index, 1)
      },
      changePageSize(value){
        if (value == "A4"){
          this.formConfig.frame.printSetting.pageWidth = 21;
          this.formConfig.frame.printSetting.pageHeight = 29;
          this.formConfig.frame.printSetting.pageDirection = "H"
        }else if (value == "B5"){
          this.formConfig.frame.printSetting.pageWidth = 17.6;
          this.formConfig.frame.printSetting.pageHeight = 25;
          this.formConfig.frame.printSetting.pageDirection = "H"
        }
      },
      getFormEventHandled(eventName) {
        return !!this.formConfig[eventName] && (this.formConfig[eventName].length > 0)
      },

      showEventCollapse() {
        if (this.designerConfig['eventCollapse'] === undefined) {
          return true
        }

        return !!this.designerConfig['eventCollapse']
      },

      editFormCss() {
        this.formCssCode = this.designer.formConfig.cssCode
        this.showEditFormCssDialogFlag = true
      },

      extractCssClass() {
        let regExp = /\..*{/g
        let result = this.formCssCode.match(regExp)
        let cssNameArray = []

        if (!!result && result.length > 0) {
          result.forEach((rItem) => {
            let classArray = rItem.split(',')  //切分逗号分割的多个class
            if (classArray.length > 0) {
              classArray.forEach((cItem) => {
                let caItem = cItem.trim()
                if (caItem.indexOf('.', 1) !== -1) {  //查找第二个.位置
                  let newClass = caItem.substring(caItem.indexOf('.') + 1, caItem.indexOf('.', 1))  //仅截取第一、二个.号之间的class
                  if (!!newClass) {
                    cssNameArray.push(newClass.trim())
                  }
                } else if (caItem.indexOf(' ') !== -1) {  //查找第一个空格位置
                  let newClass = caItem.substring(caItem.indexOf('.') + 1, caItem.indexOf(' '))  //仅截取第一、二个.号之间的class
                  if (!!newClass) {
                    cssNameArray.push(newClass.trim())
                  }
                } else {
                  if (caItem.indexOf('{') !== -1) {  //查找第一个{位置
                    let newClass = caItem.substring(caItem.indexOf('.') + 1, caItem.indexOf('{'))
                    cssNameArray.push( newClass.trim() )
                  } else {
                    let newClass = caItem.substring(caItem.indexOf('.') + 1)
                    cssNameArray.push( newClass.trim() )
                  }
                }
              })
            }
          })
        }

        //this.cssClassList.length = 0
        this.cssClassList.splice(0, this.cssClassList.length)  //清除数组必须用splice，length=0不会响应式更新！！
        this.cssClassList = Array.from( new Set(cssNameArray) )  //数组去重
      },

      saveFormCss() {
        this.extractCssClass()
        this.designer.formConfig.cssCode = this.formCssCode
        insertCustomCssToHead(this.formCssCode)
        this.showEditFormCssDialogFlag = false

        this.designer.emitEvent('form-css-updated', deepClone(this.cssClassList))
      },

      editGlobalFunctions() {
        this.functionsCode = this.designer.formConfig.functions
        this.showEditFunctionsDialogFlag = true
      },

      saveGlobalFunctions() {
        const codeHints = this.$refs.gfEditor.getEditorAnnotations()
        let syntaxErrorFlag = false
        if (!!codeHints && (codeHints.length > 0)) {
          codeHints.forEach((chItem) => {
            if (chItem.type === 'error') {
              syntaxErrorFlag = true
            }
          })

          if (syntaxErrorFlag) {
            this.$message.error(this.i18nt('designer.setting.syntaxCheckWarning'))
            return
          }
        }

        this.designer.formConfig.functions = this.functionsCode
        insertGlobalFunctionsToHtml(this.functionsCode)
        this.showEditFunctionsDialogFlag = false
      },

      editFormEventHandler(eventName) {
        this.curEventName = eventName
        this.formEventHandlerCode = this.formConfig[eventName]
        this.showFormEventDialogFlag = true
      },

      saveFormEventHandler() {
        const codeHints = this.$refs.ecEditor.getEditorAnnotations()
        let syntaxErrorFlag = false
        if (!!codeHints && (codeHints.length > 0)) {
          codeHints.forEach((chItem) => {
            if (chItem.type === 'error') {
              syntaxErrorFlag = true
            }
          })

          if (syntaxErrorFlag) {
            this.$message.error(this.i18nt('designer.setting.syntaxCheckWarning'))
            return
          }
        }
        console.log(this.curEventName)
        this.formConfig[this.curEventName] = this.formEventHandlerCode
        this.showFormEventDialogFlag = false
      },
      editFillText(){
        this.openText = true;
        this.helpDocument = this.formConfig.frame.helpDocument
      },
      submitTextForm(){
        this.openText = false;
        this.formConfig.frame.helpDocument = this.helpDocument
      },
      addReturnParams() {
        if (!Array.isArray(this.formConfig.returnParams)){
          this.formConfig.returnParams = []
        }
        this.formConfig.returnParams.push({})
      },
      goEditFuncKey(item){
        this.selectFuncKeyItem = item;
        this.functionField = null;
        this.openFuncKey = true;
      },
      submitFuncKey(){
        this.openFuncKey = false;
        this.selectFuncKeyItem.field = this.functionField
      },
      goEditReturnParam(item){
        this.selectReturnItem = item;
        this.calculation = item.expression?item.expression:"";
        this.openCalculation = true;
        const self = this;
        setTimeout(function () {
          self.$refs["calculationInput"].focus();
        }, 200);
      },
      selectCalculationField(item){
        let dom = this.$refs["calculationInput"].textarea;
        let index = dom.selectionStart;
        let label = "#"+item+"#";
        let text = this.calculation;
        const beforeCaret = text.slice(0, index);
        const afterCaret = text.slice(index);
        let calculation = beforeCaret+label+afterCaret
        this.calculation = calculation;
        this.$nextTick(() => {  //必须在DOM更新之后操作
          dom.focus();
          dom.setSelectionRange(   // 光标位置
              index + label.length,
              index + label.length
          );
        })
      },
      submitCalculation(){
        this.openCalculation = false;
        this.selectReturnItem.expression = this.calculation
      },
      deleteReturnParams(index) {
        this.formConfig.returnParams.splice(index, 1)
      },
      addSql(){
        this.sqlForm = {
          statementId: generateUUID(),
          inArgs:[{argType:"string"}],
          outArgs:[{argType:"string"}],
        }
        this.openSql = true
        this.sqlMode = "add"
      },
      selectSqlField(item){
        let dom = this.$refs["sqlInput"].textarea;
        let index = dom.selectionStart;
        let label = "#"+item+"#";
        let text = this.sqlForm.statement;
        let beforeCaret="",afterCaret="";
        if(text){
          beforeCaret = text.slice(0, index);
          afterCaret = text.slice(index);
        }
        let calculation = beforeCaret+label+afterCaret
        this.sqlForm.statement = calculation;
        this.$nextTick(() => {  //必须在DOM更新之后操作
          dom.focus();
          dom.setSelectionRange(   // 光标位置
              index + label.length,
              index + label.length
          );
        })
      },
      initArgs(args){
        let argList = [];
        args.forEach(item => {
          argList.push({
            argName:item,
            argType: "String"
          });
        })
        return argList;
      },
      addArgs(list){
        list.push({
          argType:"string"
        })
      },
      deleteArgs(list,index){
        if (list.length>1){
          list.splice(index,1)
        }
      },
      submitSql(){
/*        let statement = this.sqlForm.statement+"";
        let param = statement.match(/#(.*?)#/g);
        param = param ? param.map(item => item.replace(/#/g, '')) : [];
        let inArgsPre = this.sqlForm.inArgsPre;
        let inArgsF = [...new Set([...param, ...inArgsPre])];
        console.log(inArgsF)*/
        /*this.sqlForm.inArgs = this.initArgs(inArgsF);
        this.sqlForm.outArgs = this.initArgs(this.sqlForm.outArgsPre);*/
        if (this.sqlMode == "add") {
          if (!this.formConfig.customDBStatement){
            this.formConfig.customDBStatement = []
          }
          this.formConfig.customDBStatement.push({...this.sqlForm})
        }else {
          this.formConfig.customDBStatement[this.sqlIndex] = {...this.sqlForm}
        }
        this.openSql = false;
      },
      editSql(btn,index){
        this.sqlForm = {...btn}
        this.openSql = true
        this.sqlMode = "edit";
        this.sqlIndex = index;
      },
      deleteSql(index) {
        this.formConfig.customDBStatement.splice(index, 1)
      },
      addBtn(mode) {
        this.btnForm = {
          btnId: "btn" + generateId(),
          ord:0,
        }
        this.openBtn = true
        this.buttonMode = "add";
        this.buttonType = mode;
      },
      editBtn(type,btn,index){
        this.btnForm = {...btn}
        this.openBtn = true
        this.buttonMode = "edit";
        this.buttonType = type;
        this.buttonIndex = index;
      },
      submitBtnForm() {
        this.$refs['btnForm'].validate(valid => {
          if (valid) {
            if (this.buttonMode == "add") {
              if (this.buttonType == 'top'){
                this.formConfig.btnBar.topBtns.push({...this.btnForm})
              }else if (this.buttonType == 'in'){
                this.formConfig.btnBar.inBtns.push({...this.btnForm})
              }else if (this.buttonType == 'bottom'){
                this.formConfig.btnBar.bottomBtns.push({...this.btnForm})
              }
              this.openBtn = false;
            }else {
              if (this.buttonType == 'top'){
                this.formConfig.btnBar.topBtns[this.buttonIndex] = {...this.btnForm}
              }else if (this.buttonType == 'in'){
                this.formConfig.btnBar.inBtns[this.buttonIndex] = {...this.btnForm}
              }else if (this.buttonType == 'bottom'){
                this.formConfig.btnBar.bottomBtns[this.buttonIndex] = {...this.btnForm}
              }

              this.openBtn = false;
            }
          }
        })
      },
      moveDown(mode, index){
        let arr =[];
        if (mode == "top") {
          arr = this.formConfig.btnBar.topBtns;
        } else if (mode == "in") {
          arr = this.formConfig.btnBar.inBtns;
        } else if (mode == "bottom") {
          arr = this.formConfig.btnBar.bottomBtns;
        }
        [arr[index], arr[index + 1]] = [arr[index + 1], arr[index]];
      },
      moveUp(mode, index){
        let arr =[];
        if (mode == "top") {
          arr = this.formConfig.btnBar.topBtns;
        } else if (mode == "in") {
          arr = this.formConfig.btnBar.inBtns;
        } else if (mode == "bottom") {
          arr = this.formConfig.btnBar.bottomBtns;
        }
        [arr[index-1], arr[index]] = [arr[index], arr[index-1]];
      },
      deleteBtns(mode,index) {
        if (mode == 'top'){
          this.formConfig.btnBar.topBtns.splice(index, 1)
        }else if (mode == 'in'){
          this.formConfig.btnBar.inBtns.splice(index, 1)
        }else if (mode == 'bottom'){
          this.formConfig.btnBar.bottomBtns.splice(index, 1)
        }
      },
      changeBtnType(val){
        let btnTypeOptionsMap = {}
        this.btnTypeOptions.forEach(function (value) {
          btnTypeOptionsMap[value.value] = value.label
        })
        let btnName = btnTypeOptionsMap[val]
        this.btnForm.showName = btnName;
      },
    }
  }
</script>

<style lang="scss" scoped>
.calculationFilter.topCalculationFilter{
  height: 393px;
}
  .setting-form {
    :deep(.el-form-item__label) {
      font-size: 13px;
      //text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }

    :deep(.el-form-item--small.el-form-item) {
      margin-bottom: 10px;
    }

    .radio-group-custom {
      :deep(.el-radio-button__inner) {
        padding-left: 12px;
        padding-right: 12px;
      }
    }

    .custom-divider.el-divider--horizontal {
      margin: 10px 0;
    }
  }

  .setting-collapse {
    :deep(.el-collapse-item__content) {
      padding-bottom: 6px;
    }

    :deep(.el-collapse-item__header) {
      font-style: italic;
      font-weight: bold;
    }
  }

  .small-padding-dialog {
    :deep(.el-dialog__body) {
      padding: 6px 15px 12px 15px;
    }
  }

</style>
